package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    MinioProperties minioProperties;

    @SneakyThrows
    @Override
    public String upload(MultipartFile file) {
        InputStream inputStream = file.getInputStream();

        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();

        String originalFilename = file.getOriginalFilename();
        String filenameExtension = StringUtils.getFilenameExtension(originalFilename);
        String yyyyMMddHH = new SimpleDateFormat("yyyyMMddHH").format(new Date());
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = yyyyMMddHH + "/" + uuid + "." + filenameExtension;

        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioProperties.getBucketName())
                .object(newFileName)
                .stream(inputStream, file.getSize(), -1)
                .build();

        minioClient.putObject(putObjectArgs);

        return minioProperties.getEndpoint() + "/" + minioProperties.getBucketName() + "/" + newFileName;
    }
}
